package com.moss.cloud.common.core.utils;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.model.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class WebFluxUtil {
    /**
     * 统一filter异常返回
     * @param serverWebExchange
     * @return
     */
    public static Mono<Void> unauthorized(ServerWebExchange serverWebExchange) {
        Result<?> result = Result.fail(SystemErrorType.UNAUTHORIZED);
        String res = JSONObject.toJSONString(result);
        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
        DataBuffer buffer = serverWebExchange.getResponse()
                .bufferFactory().wrap(res.getBytes());
        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
    }

    public static Mono<Void> cryptoError(ServerWebExchange serverWebExchange) {
        Result<?> result = Result.fail(SystemErrorType.ARGUMENT_NOT_VALID);
        String res = JSONObject.toJSONString(result);
        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
        DataBuffer buffer = serverWebExchange.getResponse()
                .bufferFactory().wrap(res.getBytes());
        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
    }
}
